﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using EpiNEXT.Services.Fields;

namespace EpiNEXT.Services.Collections
{
    public class RecordCollection : ObservableCollection<Record>
    {
        #region Members
        private SortedDictionary<string, Record> _master = new SortedDictionary<string, Record>(StringComparer.OrdinalIgnoreCase);
        #endregion // Members

        #region Properties
        /// <summary>
        /// Type Name
        /// </summary>
        /// <param name="name">id</param>
        /// <returns>NamedObjectCollection</returns>
        public Record this[string id]
        {
            get
            {
                return _master[id];
            }
        }

        /// <summary>
        /// Gets the form this collection belongs to
        /// </summary>
        public DataEntryInstrument Form { get; set; }
        #endregion // Properties

        #region Methods
        public virtual bool Contains(string id)
        {
            return _master.ContainsKey(id.ToLower());
        }

        protected override void InsertItem(int index, Record item)
        {
            //return;

            base.InsertItem(index, item);

            #region Input Validation
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }
            #endregion // Input Validation

            _master.Add(item.Id.ToString(), item);
        }

        protected override void ClearItems()
        {
            base.ClearItems();
            _master.Clear();
        }

        protected override void RemoveItem(int index)
        {
            Record recordToRemove = this[index];
            _master.Remove(recordToRemove.Id.ToString());
            base.RemoveItem(index);
        }

        protected override void SetItem(int index, Record item)
        {
            #region Input Validation
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }
            #endregion // Input Validation

            Record recordToChange = this[index];
            _master.Remove(recordToChange.Id.ToString());

            _master.Add(item.Id.ToString(), item);

            base.SetItem(index, item);
        }
        #endregion // Methods
    }
}
